package com.goalias.aop;

import com.goalias.exception.BizException;
import com.goalias.exception.ExceptionEnum;
import com.goalias.feign.UserClient;
import com.goalias.feign.domain.User;
import com.goalias.feign.domain.UserInfo;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class AuthorizedAspect {

    @Resource
    private UserClient userClient;

    @Pointcut("@annotation(Authorized)")
    public void authorizedAspect() {
    }

    @Before(value = "authorizedAspect()")
    public void checkAuthorization(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Authorized authorized = method.getAnnotation(Authorized.class);
        UserInfo userInfo = UserInfo.get();

        if (userInfo == null) {
            throw new BizException(ExceptionEnum.NEED_LOGIN);
        }
        String requiredRole = authorized.role();
        if (!requiredRole.isEmpty()) {
            User user = userClient.info(userInfo.getId());
            String type = user.getType();
            String userRole = type.equals("1") ? "ADMIN" : "USER";
            if (!requiredRole.equals(userRole)) {
                throw new BizException(ExceptionEnum.NO_OPERATOR_AUTH);
            }
        }
    }
}
